<template>
  <div>

<el-container>
  <el-header>
      <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/projects' }">项目</el-breadcrumb-item>

          <el-breadcrumb-item><a href="/projects">文档列表</a></el-breadcrumb-item>
          </el-breadcrumb>


          <!--分栏展示按钮  -->
      <br>
      <el-row :gutter="0">

      <el-col :span="3"><div class="block1">
        <el-button type="primary" @click="openPage">图形设计</el-button>
      </div></el-col>

      <el-col :span="3"><div class="block2">
        <el-button type="primary" @click="enterFile" disabled>文档列表</el-button>
        </div></el-col>

      <el-col :span="3"><div class="block3">
        <el-button type="primary" @click="enterUML">UML设计</el-button>
        </div></el-col>
        
      </el-row>


  </el-header>


<!-- main -->

  <el-main>

        <el-card class="box-card">
      <div slot="header" class="clearfix">

         
        <span> 文档列表</span>
      </div>
      <div class="el-table">
        <el-table :data="docList" style="width: 100%;" border stripe>
          <el-table-column label="文档标题" prop="title">
            <template v-slot="scope">
              <el-link type="primary" @click="showDetailFn(scope.row.title)">{{scope.row.title}}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="发表时间" prop="settime"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="danger" size="mini" @click="removeFn(row.title)">删除</el-button>
              <el-button type="success" size="mini" @click="rewriteFn(row.title)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <div class="search-box">
        <el-form :inline="true" :model="q" :rules="pubFormRules" ref="selectRef">
          <el-form-item label="文档模板" prop="template">
            <el-select v-model="q.Template" placeholer="请选择模板" size="small">
              <el-option label="空白" value="empty"></el-option>
              <el-option label="会议纪要" value="meeting"></el-option>
              <el-option label="项目计划" value="plan"></el-option>
              <el-option label="工作总结" value="summary"></el-option>
            </el-select>

          </el-form-item>
          <el-form-item label="文档标题" style="margin-left: 15px;" prop="title">
            <el-input v-model="q.title" placeholder="请输入标题"></el-input>

          </el-form-item>
<!--          <el-form-item>-->
<!--            <el-button type="primary" size="small">筛选</el-button>-->
<!--            <el-button type="info" size="small">重置</el-button>-->
<!--          </el-form-item>-->
        </el-form>
        <el-button type="primary" size="small" class="btn-pub" @click="showPubDialogFn">新建</el-button>
      </div>
    </el-card>
<!--发表文档-->
    <el-dialog  :visible.sync="pubDialogVisible" :modal-append-to-body="false"
               fullscreen :before-close="handleClose" @close="dialogCloseFn">
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
<!--        <el-form-item label="文档标题" prop="title">-->
<!--          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>-->

<!--        </el-form-item>-->
<!--        <el-form-item label="文章分类" prop="cate_id">-->
<!--          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">-->
<!--            <el-option label="区域一" value="Shanghai"></el-option>-->
<!--            <el-option label="区域二" value="Beijing"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="" prop="content">
<!--          <link href="https://cdn.quilljs.com/1.3.4/quill.snow.css" rel="stylesheet">-->
<!--          <quill-editor v-model="pubForm.content" ></quill-editor>-->
          <editor
              :key="tinymceFlag"
              ref="editor"
              v-model="pubForm.content"
              :init="tinymceInit">
          </editor>
          <vue-html2pdf
              :show-layout="false"
              :float-layout="true"
              :enable-download="true"
              :preview-modal="false"
              :paginate-elements-by-height="1400"

              :pdf-quality="2"
              :manual-pagination="false"
              pdf-format="a4"
              pdf-orientation="landscape"
              pdf-content-width="800px"
              @progress="onProgress($event)"
              @hasStartedGeneration="hasStartedGeneration()"
              @hasGenerated="hasGenerated($event)"
              ref="html2Pdf"

          >
            <section slot="pdf-content">
              <!-- PDF Content Here -->
              <span id="report" v-html="pubForm.content"></span>
            </section>
          </vue-html2pdf>

<!--          <Tinymce ref="tinymce" v-model="pubForm.content"  />-->

          <!--          <div id="editor">-->
        </el-form-item>
        <el-form-item>
<!--          <el-button type="primary" @click="pubArticleFn">发布</el-button>-->
          <el-button type="success" size="small" @click="handleSaveToPdf">保存为Pdf</el-button>
          <el-button type="primary" size="small" @click="pubArticleFn">发布</el-button>
        </el-form-item>

      </el-form>

    </el-dialog>
<!--修改文档-->
    <el-dialog :visible.sync="rewriteVisible" :modal-append-to-body="false"
               fullscreen :before-close="handleClose" @close="dialogCloseFn">
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
        <el-form-item label="" prop="content">
<!--          <quill-editor v-model="pubForm.content" ></quill-editor>-->
          <editor
              :key="tinymceFlag"
              ref="editor"
              v-model="pubForm.content"
              :init="tinymceInit">
          </editor>
          <vue-html2pdf
              :show-layout="false"
              :float-layout="true"
              :enable-download="true"
              :preview-modal="false"
              :paginate-elements-by-height="1400"
              filename=""
              :pdf-quality="2"
              :manual-pagination="false"
              pdf-format="a4"
              pdf-orientation="landscape"
              pdf-content-width="800px"
              @progress="onProgress($event)"
              @hasStartedGeneration="hasStartedGeneration()"
              @hasGenerated="hasGenerated($event)"
              ref="html2Pdf"

          >
            <section slot="pdf-content">
              <!-- PDF Content Here -->
              <span id="report" v-html="pubForm.content"></span>
            </section>
          </vue-html2pdf>

<!--          <Tinymce ref="tinymce" v-model="pubForm.content"  />-->

          <!--按钮-->

<!--          <el-button type="primary" @click="handleSaveToWord">保存为Word</el-button>-->
        </el-form-item>
        <el-form-item>
          <el-button type="success" size="small" @click="handleSaveToPdf">保存为Pdf</el-button>
          <el-button type="primary" size="small" @click="pubArticleFn">发布</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="文档详情" :visible.sync="detailVisible" width="80%">
      <div v-html="docDetail" class="detail-box"></div>
    </el-dialog>

  </el-main>
  </el-container>
   
 


  </div>


</template>

<script>
import qs from "qs";
import Editor from "@tinymce/tinymce-vue";
import VueHtml2pdf from 'vue-html2pdf';
export default {
  name: 'Projects',
  components:{
    VueHtml2pdf,
    'editor': Editor
  },
  activated() {
    this.tinymceFlag++
  },
  data(){
    return{
      tinymceFlag: 1,
      tinymceInit: {},
      rewriteVisible:false,
      detailVisible: false,
      docDetail: {},
      pubForm:{
        title:'',
        cate_id:'',
        content:''
      },
      pubFormRules:{
        title: [
          {required: true, message: '请输入文章标题', trigger: 'blur'},
          {min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur'}
        ],
        //cate_id: [{required: true, message: '请输入文章标题', trigger: 'blur'}],
        content: [{required: true, message: '请输入文章内容', trigger: 'blur'}],
        // template: [{required: true, message: '请选择模板', trigger: 'change'}]
      },
      q:{
        Template:'',
        title:''
      },
      pubDialogVisible: false,
      docList: [],
    }
  },

  created() {
    this.init();
    this.initEditor();
  },

  methods: {

    // htmlToPdfOptions() {
    //   return {
    //     margin: 0,
    //
    //     filename: "我是pdf.pdf",
    //
    //     image: {
    //       type: "jpeg",
    //       quality: 0.98,
    //     },
    //
    //     enableLinks: true,
    //
    //     html2canvas: {
    //       scale: 2,
    //       useCORS: true,
    //     },
    //
    //     jsPDF: {
    //       unit: "in",
    //       format: 'a4',
    //       orientation: 'portrait',
    //     },
    //   };
    // },
    handleSaveToPdf() {
      this.$refs.html2Pdf.generatePdf()
    },
    onProgress() {

    },
    hasStartedGeneration() {

    },
    hasGenerated() {

    },
    initEditor() {
      this.tinymceInit = {
        language: 'zh_CN',
        height: 580,
        width: 1200,
        branding: false,
        fontsize_formats:
          '12px 13px 14px 15px 16px 17px 18px 19px 20px 22px 24px 26px 28px 30px 32px 34px 40px 50px',
        toolbar:
          'formatselect fontselect | bold italic strikethrough  fontsizeselect | link image | forecolor backcolor' +
            ' | numlist bullist | table hr',
        plugins:
          'lists table hr',
      }
      this.tinymceFlag++
    },
    rewriteFn(docTitle){
      this.$axios({
        method:'post',
        url: '/projects/workload',
        data: qs.stringify({
          usertoken: this.$store.getters.getUser.user.usertoken,
          teamtoken:this.$store.getters.getGroup.group.grouptoken,
          protoken:this.$store.getters.getProject.project.projecttoken,
          title: docTitle
        })
      }).then(res => {                  /* res 是 response 的缩写 */
        this.pubForm.content = res.data.contents
        console.log(res)
      })
          .catch(err => {                 /* 请求若出现路由找不到等其它异常，则在终端输出错误信息 */
            console.log(err);
          })
      //quillEditor.inserted(this.docDetail)

      this.rewriteVisible = true
      this.q.title = docTitle
    },
    showPubDialogFn() {
      //console.log(this.q.Template)
      this.$refs.selectRef.validate(async valid => {
        if(valid){
          // this.$axios({
          //   method: 'post',
          //   url: '/template/list',
          //   data: qs.stringify({
          //     usertoken: this.$store.getters.getUser.user.usertoken,
          //     sort: 'name',
          //     search: ''
          //   })
          // }).then(res => {
          //   console.log(res)
          // })
          //     .catch(err => {
          //       console.log(err)
          //     })
          let templateName = ''
          if(this.q.Template==='empty'){
            templateName = '空白'
          }
          else if(this.q.Template==='meeting'){
            templateName = '会议纪要'
          }
          else if(this.q.Template==='summary'){
            templateName = '工作周报'
          }
          else {
            templateName = '项目计划'
          }
          if(templateName.length!==0){
            console.log(templateName+"@"+this.$store.getters.getUser.user.usertoken)
            this.$axios({
              method: 'post',
              url: '/template/load',
              data: qs.stringify({
                usertoken: this.$store.getters.getUser.user.usertoken,
                templatename: templateName+"@0",
              })
            }).then(res => {
              console.log(res)
              this.pubForm.content = res.data.contents

            })
                .catch(err => {
                  console.log(err)
                })
          }
          else {
            this.pubForm.content = ''
          }
          this.pubForm.title = ''
          this.pubDialogVisible = true
        }
        else {
          return false
        }
      })

    },
    init(){
      const userToken = this.$store.getters.getUser.user.usertoken;
      const teamToken = this.$store.getters.getGroup.group.grouptoken;
      const proToken = this.$store.getters.getProject.project.projecttoken;
      console.log(userToken)
      console.log(teamToken)
      console.log(proToken)
      this.$axios({
        method:'post',
        url:'/projects/worklist',
        data: qs.stringify({
          usertoken: userToken,
          teamtoken: teamToken,
          protoken: proToken,
          sort: '',
          search: '',
        })
      }).then(res => {                  /* res 是 response 的缩写 */
        this.docList = res.data.message
        console.log(res)
      })
          .catch(err => {                 /* 请求若出现路由找不到等其它异常，则在终端输出错误信息 */
            console.log(err);
          })
    },

    dialogCloseFn() {
      this.$refs.pubFormRef.resetFields()
      this.$refs.selectRef.resetFields()
    },
    async handleClose(done) {
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult === 'cancel')return
      done()
    },
    pubArticleFn(){
      this.$refs.pubFormRef.validate(async valid =>{
        if(valid){

          var n=new Date().toLocaleString().replaceAll('/','-');
          console.log(n);
          this.$axios({
            method: 'post',
            url: '/projects/worksave',
            data: qs.stringify({
              usertoken: this.$store.getters.getUser.user.usertoken,
              teamtoken:this.$store.getters.getGroup.group.grouptoken,
              protoken:this.$store.getters.getProject.project.projecttoken,
              title: this.q.title,
              time: n,
              contents: this.pubForm.content
            })
          }).then(res => {                  /* res 是 response 的缩写 */
                console.log(res);
              this.q.title = ''
              this.pubForm.content = ''
              this.pubDialogVisible = false
              this.rewriteVisible = false
              this.init()
              })
              .catch(err => {                 /* 请求若出现路由找不到等其它异常，则在终端输出错误信息 */
                console.log(err);
              })


        }
        else{
          return false
        }
      })
    },
    pubTemplateFn(){
      this.$refs.pubFormRef.validate(async valid =>{
        if(valid){

          var n=new Date().toLocaleString().replaceAll('/','-');
          console.log(n);
          this.$axios({
            method: 'post',
            url: '/template/saveoff',
            data: qs.stringify({
              usertoken: this.$store.getters.getUser.user.usertoken,
              // teamtoken:this.$store.getters.getGroup.group.grouptoken,
              // protoken:this.$store.getters.getProject.project.projecttoken,
              templatename: this.pubForm.title,
              //time: n,
              contents: this.pubForm.content
            })
          }).then(res => {                  /* res 是 response 的缩写 */
            console.log(res);
            this.pubForm.title = ''
            this.pubForm.content = ''
            this.pubDialogVisible = false
            this.rewriteVisible = false
            this.init()
          })
              .catch(err => {                 /* 请求若出现路由找不到等其它异常，则在终端输出错误信息 */
                console.log(err);
              })


        }
        else{
          return false
        }
      })
    },
    showDetailFn(docTitle){
      console.log(docTitle)
      this.$axios({
        method:'post',
        url: '/projects/workload',
        data: qs.stringify({
          usertoken: this.$store.getters.getUser.user.usertoken,
          teamtoken:this.$store.getters.getGroup.group.grouptoken,
          protoken:this.$store.getters.getProject.project.projecttoken,
          title: docTitle
        })
      }).then(res => {                  /* res 是 response 的缩写 */
        this.docDetail = res.data.contents
        console.log(res)
      })
          .catch(err => {                 /* 请求若出现路由找不到等其它异常，则在终端输出错误信息 */
            console.log(err);
          })
      this.detailVisible = true
    },
    removeFn(docTitle){
      this.$axios({
        method:'post',
        url: 'projects/workdrop',
        data:qs.stringify({
          usertoken: this.$store.getters.getUser.user.usertoken,
          teamtoken:this.$store.getters.getGroup.group.grouptoken,
          protoken:this.$store.getters.getProject.project.projecttoken,
          title: docTitle
        })
      }).then(res =>{
        console.log(res)
        this.init()
        this.$message.success('删除文档成功')
      })
          .catch(err => {
            console.log(err)
            this.$message.error(err)
          })

    },
     openPage(){
      //跳转至原型设计页面
      setTimeout(() => {this.$router.push("/graphdesign")}, 10);
      // window.open('http://localhost:8080/graphdesign')

    },
    enterFile(){
      //跳转至文档页面
      setTimeout(() => {this.$router.push("/new")}, 10);
      // window.open('http://localhost:8080/new')
    },
     enterUML(){
      //跳转至uml设计页面
      setTimeout(() => {this.$router.push("/uml")}, 10);
      // window.open('http://localhost:8080/new')
    }
  },
  // mounted() {
  //   tinymce.init({
  //     selector: '#mytextarea',
  //     language: 'zh_CN',
  //     branding: false,
  //     plugins: 'save',
  //     toolbar: 'save',
  //   })
  // },
  mounted() {

  }

}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub{
    margin-top: 5px;
  }
}
 ::v-deep .ql-editor{
  min-height: 300px;
}

.block1{
  margin-left: 0px;
  padding-left: 0px;
}

</style>
